package yannan.voiplock4ble.task;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;

import com.tencent.bugly.crashreport.CrashReport;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.List;

import yannan.voiplock4ble.LoginActivity;
import yannan.voiplock4ble.MainActivity;
import yannan.voiplock4ble.SplashActivity;
import yannan.voiplock4ble.base.MyEnum;
import yannan.voiplock4ble.base.MyApplication;
import yannan.voiplock4ble.bean.LockBean;
import yannan.voiplock4ble.bean.LockBeanDao;
import yannan.voiplock4ble.bean.UserAccount;
import yannan.voiplock4ble.bean.UserBean;
import yannan.voiplock4ble.db.DaoUtils;
import yannan.voiplock4ble.db.daomanager.LockBeanDaoManager;
import yannan.voiplock4ble.db.daomanager.UserAccountDaoManager;
import yannan.voiplock4ble.db.daomanager.UserBeanDaoManager;
import yannan.voiplock4ble.net.NetUtils;
import yannan.voiplock4ble.net.base.NetworkCallBack;
import yannan.voiplock4ble.utils.PopShowUtils;
import yannan.voiplock4ble.utils.StringEncrypt;
import yannan.voiplock4ble.utils.ToastUtils;

/**
 * 说明：登录线程
 * 作者：mainTel
 * 时间：2016/11/22 15:53
 * 备注：
 */
public class LoginTask extends Thread {

    String account;
    String pwd;
    Activity mContext;
    boolean isShowPro;
    boolean isRemeberPassword;

    public static LoginTask create(Activity mContext, String account, String pwd, boolean isRemeberPassword, boolean isShowPro) {
        LoginTask loginTask = new LoginTask();
        loginTask.account = account;
        loginTask.mContext = mContext;
        loginTask.pwd = pwd;
        loginTask.isRemeberPassword = isRemeberPassword;
        loginTask.isShowPro = isShowPro;
        return loginTask;
    }

    @Override
    public void run() {
        if (isShowPro) {
            mContext.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    PopShowUtils.showProgress(mContext);
                }
            });
        }
        //密码是不是要加密
        if (isShowPro) {
            pwd = StringEncrypt.EncryptBySHA_256(pwd);
        }
        NetUtils.getNetworkService().login(account, pwd, 1).enqueue(new NetworkCallBack<UserBean>() {
            @Override
            public void onSuc(UserBean resBody) {
                MyApplication.getInterface().userBean = resBody;
                DaoUtils.getDao(UserBeanDaoManager.class).deleteAll();
                DaoUtils.getDao(UserBeanDaoManager.class).insert(resBody);
                DaoUtils.getDao(UserAccountDaoManager.class).deleteAll();
                //是否保存密码
                if (!isRemeberPassword) {
                    pwd = "";
                }
                getLockList(resBody.userId);
                CrashReport.putUserData(mContext, "User", resBody.toString());
                DaoUtils.getDao(UserAccountDaoManager.class).insert(new UserAccount(account, pwd));
            }

            @Override
            public void onFail(String msg) {
                stopProgress();
                if (msg != null && msg.contains("登录失败！账号或密码不正确")) {
                    ToastUtils.showToast(mContext, "登录失败！账号或密码不正确");
                } else {
                    ToastUtils.showToast(mContext, "登录失败");
                }
                if (!isShowPro) {  //说明是在启动页 跳转入登录页
                    jump2Login();
                }
            }
        });
    }

    private void jump2Login() {
        EventBus.getDefault().post("closeLoginActivity");
        Intent intent = new Intent(mContext, LoginActivity.class);
        mContext.startActivity(intent);
    }

    private void getLockList(String userId) {
        NetUtils.getNetworkService().getLockList(userId)
                .enqueue(new NetworkCallBack<List<LockBean>>() {
                    @Override
                    public void onSuc(List<LockBean> resBody) {
                        for (LockBean lockBean : resBody) {
                            lockBean.userId = MyApplication.getInterface().userBean.userId;
                        }
                        jump2Main(resBody);
                    }

                    @Override
                    public void onFail(String msg) {
                        jump2Main(null);
                    }
                });
    }

    /**
     * 获取本地所列表信息
     */
    private void getLocalLockList() {
        List<LockBean> lockBeans = DaoUtils.getDao(LockBeanDaoManager.class).getQueryBuilder()
                .where(LockBeanDao.Properties.UserId.eq(MyApplication.getInterface().userBean.userId))
                .build().list();
        jump2Main(lockBeans);
    }

    private void jump2Main(List<LockBean> resBody) {
        Intent intent = new Intent(mContext, MainActivity.class);
        intent.putExtra(MyEnum.MainEnum.lockBeanList.toString(), (Serializable) resBody);
        DaoUtils.getDao(LockBeanDaoManager.class).deleteAll();
        if (resBody != null && resBody.size() != 0) {
            intent.putExtra(MyEnum.MainEnum.lockBeanList.toString(), (Serializable) resBody);
            DaoUtils.getDao(LockBeanDaoManager.class).insertList(resBody);

        }
        mContext.startActivity(intent);
        int i = 0;
        if (resBody != null)
            for (LockBean lockBean : resBody) {
                CrashReport.putUserData(mContext, "LockBean" + i++, lockBean.toStringMy());
            }
        EventBus.getDefault().post("closeLoginActivity");
        stopProgress();
    }

    private void stopProgress() {
        mContext.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                PopShowUtils.dimssProgress();
                if (mContext instanceof LoginActivity) {
                    ((LoginActivity) mContext).btn_sign_in.setEnabled(true);
                } else if (mContext instanceof SplashActivity) {
                    mContext.finish();
                }
            }
        });
    }
}
